package jdk8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

import org.junit.Test;

public class ForeachTest {
    /**
     * 求和是线程安全的
     */
    @Test
    public void test01() {
        long startTime = System.currentTimeMillis();
        System.out.println("sum:" + LongStream.range(0, 100000000L).parallel().sum());
        System.out.println("并行处理：" + (System.currentTimeMillis() - startTime));

        startTime = System.currentTimeMillis();
        System.out.println("sum:" + LongStream.range(0, 100000000L).sum());
        System.out.println("串行处理：" + (System.currentTimeMillis() - startTime));
    }

    @Test
    public void test02() {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        List<Integer> list3 = new ArrayList<>();
        Lock lock = new ReentrantLock();

        IntStream.range(0, 10000).forEach(list1::add);

        IntStream.range(0, 10000).parallel().forEach(list2::add);

        IntStream.range(0, 10000).forEach(i -> {
            lock.lock();
            try {
                list3.add(i);
            } finally {
                lock.unlock();
            }
        });

        System.out.println("串行执行的大小：" + list1.size());
        System.out.println("并行执行的大小：" + list2.size());
        System.out.println("加锁并行执行的大小：" + list3.size());
    }
}
